package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import bean.Customer;
import common.util.DBUtils;
import dao.UserDao;

public class UserDaoImpl implements UserDao {

	@Override
	public boolean insert(Customer t) throws SQLException {
				//① 创建连接
				Connection conn = DBUtils.getConnection();
				
				//② 数据操作
				String sql = "insert into customer values(?, ?, ?, ?, ?, ?, ?, ?)";
				PreparedStatement psmt = conn.prepareStatement(sql);
				psmt.setString(1, t.getCustomerId());
				psmt.setString(2, t.getcName());
				psmt.setString(8, t.getcPassword());
				
				java.util.Date birth = t.getcBirthDate();
				if (birth != null) {
					long time = birth.getTime();
					java.sql.Date sqlBirth = new java.sql.Date(time);	
					psmt.setDate(4, sqlBirth);	
				} else {
					psmt.setDate(4, null);	
				}		
				
				psmt.setString(3, t.getcGender());
				psmt.setString(5, t.getcCardID());
				psmt.setString(6, t.getcPhone());
				psmt.setString(7, t.getcRemark());
				int index = psmt.executeUpdate();
				
				//③ 关闭资源
				DBUtils.closeResource(conn, psmt);
				
				return index > 0;
	}

	@Override
	public void deleteById(String id) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Customer t) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public Customer queryByid(String id) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Customer> queryAll() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Customer queryByNameAndPsw(String name, String password) throws SQLException {
		//① 创建连接
			Connection conn = DBUtils.getConnection();
			
			//② 数据操作
			//准备sql语句
			String sql = "select * from customer where cname=? and cpassword = ?";
			//获得数据库操作的句柄
			PreparedStatement psmt = conn.prepareStatement(sql);
			//设置数据
			psmt.setString(1, name);
			psmt.setString(2, password);
			//执行数据库操作
			ResultSet rs = psmt.executeQuery();
			
			//③ 遍历结果集
			Customer customer = null;
			if(rs.next()) {
				//取数据
				String customerId = rs.getString("customerId");
				String cName = rs.getString("cName");
				String cPassword = rs.getString("cPassword");
				Date cBirthDate = rs.getDate("cBirth");
				String cGender = rs.getString("cGender");
				String cCardID = rs.getString("cCardID");
				String cPhone = rs.getString("cPhone");
				String cRemark = rs.getString("cRemarks");
				customer = new Customer(customerId, cName, cPassword, cBirthDate, cGender,cCardID,cPhone, cRemark);
			}
			
			//④ 关闭资源
			DBUtils.closeResource(conn, psmt, rs);
			
			return customer;
		}

}
